Micron Document




JavaScript syntax
part 11/59 · 107.4 KB total
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Variables declared outside a scope are global. If a variable is declared in a higher scope, it can be accessed by child scopes.

When JavaScript tries to resolve an identifier, it looks in the local scope. If this identifier is not found, it looks in the next outer scope, and so on along the scope chain until it reaches the global scope where global variables reside. If it is still not found, JavaScript will raise a ReferenceError exception.

When assigning an identifier, JavaScript goes through exactly the same process to retrieve this identifier, except that if it is not found in the global scope, it will create the "variable" in the scope where it was created.cite-ref-9[9] As a consequence, a variable never declared will be global, if assigned. Declaring a variable (with the keyword var) in the global scope (i.e. outside of any function body (or block in the case of let/const)), assigning a never declared identifier or adding a property to the global object (usually window) will also create a new global variable.

Note that JavaScript's strict mode forbids the assignment of an undeclared variable, which avoids global namespace pollution.

Examples

Here are some examples of variable declarations and scope:

var x1 = 0; // A global variable, because it is not in any function
let x2 = 0; // Also global, this time because it is not in any block
function f() {
var z = 'foxes', r = 'birds'; // 2 local variables
m = 'fish'; // global, because it was not declared anywhere before
function child() {
var r = 'monkeys'; // This variable is local and does not affect the "birds" r of the parent function.
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────